#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include "../include/memory_monitor.h"

#define PROC_MEMINFO "/proc/meminfo"
#define MAX_LINE_LENGTH 256

static pthread_t monitor_thread;
static Memory_Usage current_usage = {0};
static pthread_mutex_t usage_mutex = PTHREAD_MUTEX_INITIALIZER;
static Memory_Monitor_Args* monitor_args = NULL;

// 读取内存信息
static int read_memory_info(Memory_Usage* usage) {
    FILE* fp;
    char line[MAX_LINE_LENGTH];
    char name[32];
    unsigned long value;
    
    fp = fopen(PROC_MEMINFO, "r");
    if (!fp) {
        return -1;
    }
    
    while (fgets(line, sizeof(line), fp)) {
        if (sscanf(line, "%s %lu", name, &value) == 2) {
            if (strcmp(name, "MemTotal:") == 0) {
                usage->total = value;
            } else if (strcmp(name, "MemFree:") == 0) {
                usage->free = value;
            } else if (strcmp(name, "Buffers:") == 0) {
                usage->buffers = value;
            } else if (strcmp(name, "Cached:") == 0) {
                usage->cached = value;
            }
        }
    }
    
    fclose(fp);
    
    // 计算已使用内存和内存使用率
    usage->used = usage->total - usage->free - usage->buffers - usage->cached;
    usage->usage_percent = ((double)usage->used / usage->total) * 100.0;
    
    return 0;
}

// 内存监控线程函数
void* memory_monitor_thread(void* arg) {
    Memory_Monitor_Args* args = (Memory_Monitor_Args*)arg;
    
    while (args->running) {
        Memory_Usage usage;
        
        if (read_memory_info(&usage) == 0) {
            pthread_mutex_lock(&usage_mutex);
            current_usage = usage;
            pthread_mutex_unlock(&usage_mutex);
        }
        
        sleep(args->interval);
    }
    
    return NULL;
}

// 初始化内存监控
int init_memory_monitor(void) {
    monitor_args = malloc(sizeof(Memory_Monitor_Args));
    if (!monitor_args) {
        return -1;
    }
    
    monitor_args->interval = 1;  // 默认1秒更新一次
    monitor_args->running = 1;
    
    if (pthread_create(&monitor_thread, NULL, memory_monitor_thread, monitor_args) != 0) {
        free(monitor_args);
        monitor_args = NULL;
        return -1;
    }
    
    return 0;
}

// 清理内存监控
void cleanup_memory_monitor(void) {
    if (monitor_args) {
        monitor_args->running = 0;
        pthread_join(monitor_thread, NULL);
        free(monitor_args);
        monitor_args = NULL;
    }
    
    pthread_mutex_destroy(&usage_mutex);
}

// 获取当前内存使用情况
Memory_Usage get_memory_usage(void) {
    Memory_Usage usage;
    
    pthread_mutex_lock(&usage_mutex);
    usage = current_usage;
    pthread_mutex_unlock(&usage_mutex);
    
    return usage;
} 